<template>
  <div style="width: 60%; margin: 10px auto">
    <div class="card" style="margin-bottom: 5px; padding: 20px">
      <div style="margin-bottom: 20px; font-size: 24px; font-weight: bold">我的收货地址</div>
      <div style="margin-bottom: 10px">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </div>
      <el-table stripe :data="data.tableData">
        <el-table-column prop="name" label="收货人名称"></el-table-column>
        <el-table-column prop="address" label="收货地址"></el-table-column>
        <el-table-column prop="phone" label="收货电话"></el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" circle :icon="Edit" @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" circle :icon="Delete" @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination
          @current-change="load"
          @size-change="handleSizeChange"
          background layout="total, prev, pager, next, jumper, sizes"
          :page-sizes="[1, 3, 5, 10, 15, 20, 30]"
          :page-size="data.pageSize"
          v-model:current-page="data.pageNum"
          :total="data.total"/>
    </div>

    <el-dialog title="收货地址" v-model="data.formVisible" width="50%" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="100px" style="padding: 20px">
        <el-form-item prop="name" label="收货人姓名">
          <el-input v-model="data.form.name" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>
        <el-form-item prop="address" label="收货地址">
          <el-input v-model="data.form.address" placeholder="请输入收货地址"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="收货电话">
          <el-input v-model="data.form.phone" placeholder="请输入收货电话"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>

  import {reactive, ref} from "vue";
  import request from "@/utils/request.js";
  import {ElMessage, ElMessageBox} from "element-plus";
  import {Delete, Edit} from "@element-plus/icons-vue";


  const data = reactive({
    pageNum: 1,
    pageSize: 10,
    tableData: [],
    total: null,
    ids: [],
    formVisible: false,
    form: {},
    rules: {
      name: [
        { required: true, message: '收货人姓名不能为空', trigger: 'blur' },
        { min: 2, max: 10, message: '姓名长度2-10个字符', trigger: 'blur' }
      ],
      address: [
        { required: true, message: '收货地址不能为空', trigger: 'blur' },
        { min: 5, max: 50, message: '收货人地址长度5-50个字符', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        {
          pattern: /^1[3-9]\d{9}$/,
          message: '请输入正确的手机号码',
          trigger: 'blur'
        }
      ]
    }
  })

  const formRef = ref()

  const load = () => {
    request.get('/address/pageQuery', {
      params: {
        pageNum: data.pageNum,
        pageSize: data.pageSize,
      }
    }).then(res => {
      if (res.code === '200') {
        data.tableData = res.data?.list || []
        data.total = res.data?.total
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
  load()

  const handleAdd = () => {
    data.form = {}
    data.formVisible = true
  }

  const handleEdit = (row) => {
    data.form = JSON.parse(JSON.stringify(row))
    data.formVisible = true
  }

  const add = () => {
    request.post('/address/add', data.form).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功')
        data.formVisible = false
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  const update = () => {
    request.put('/address/update', data.form).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功')
        data.formVisible = false
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  const save = () => {
    formRef.value.validate(valid => {
      if (valid) {
        data.form.id ? update() : add()
      }
    })
  }

  const del = (id) => {
    ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', {type: 'warning'}).then(res => {
      request.delete('/address/delete/' + id).then(res => {
        if (res.code === '200') {
          ElMessage.success("删除成功")
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }).catch(err => {
      console.error(err)
    })
  }

  const handleSizeChange = (newPageSize) => {
    data.pageSize = newPageSize
    data.pageNum = 1
    load()
  }

</script>